import { Injectable, HttpException, NotFoundException } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from '../entity/User';
import { InjectRepository } from '@nestjs/typeorm';
import { UserCreateDto } from '../dto/UserCreateDto';
import * as bcrypt from 'bcrypt';
import { FindUserType } from 'src/constants';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private userRepository: Repository<User>,
  ) {}

  async create(user: UserCreateDto) {
    const exitUser = await this.findByName(user.username,FindUserType.Create);
    if (exitUser) {
      throw new HttpException('用户名已存在', 400);
    }
    const newUser = new User();
    newUser.username = user.username;
    const salt = await bcrypt.genSalt(10);
    newUser.encrytedPassword = await bcrypt.hash(user.password, salt);
    return await this.userRepository.save(newUser);
  }

  async findByName(name: string,type:FindUserType = FindUserType.Find) {
    const user = await this.userRepository.findOneBy({
      username: name,
    });
    if(type === FindUserType.Find && !user) throw new NotFoundException('用户不存在')
    return user
  }
  async list(){
    return await this.userRepository.find()
  }
}
